package com.zhou.framework.job;

import com.zhou.framework.common.SpringFactory;
import com.zhou.framework.util.SettingUtil;
import com.zhou.util.DateUtil;
import com.zhou.framework.dao.Log;
import com.zhou.framework.quartz.job.JobTask;
import com.zhou.org.dao.BlackList;
import com.zhou.org.service.BlackListService;
import com.zhou.org.service.LogService;
import com.zhou.util.TimeUtil;
import org.apache.commons.collections.MapUtils;
import org.quartz.JobExecutionContext;

import java.util.*;


/**
 * 检查日志访问状态，频繁异常访问加入黑名单
 */
public class AccessLogCheckJob extends JobTask {
    @Override
    public void run(JobExecutionContext context) {
        LogService logService = SpringFactory.getBean(LogService.class);
        Date now = context == null ? new Date() : context.getFireTime();
        int max = SettingUtil.getInteger("system","forbiddenTimes",10);
        int forbiddenMinutes = SettingUtil.getInteger("system","forbiddenMinutes",10);
        List<Log> errorList = logService.getErrorLog(DateUtil.getLastDayDate(now,1),now);
        if(errorList.size() > 0){
            Map<String,Integer> countMap = new HashMap<>(20);
            Set<String> detack = new HashSet<>(5);
            for (Log objectMap : errorList) {
                String ip = objectMap.getIp();
                if(!detack.contains(ip)){
                    int c = MapUtils.getIntValue(countMap,ip,0);
                    if(++ c > max){
                        detack.add(ip);
                    }else{
                        countMap.put(ip, c);
                    }
                }
            }
            if(detack.size() > 0){
                BlackListService blackService = SpringFactory.getBean(BlackListService.class);
                Collection<BlackList> items = blackService.listByIds(detack);
                Map<String,BlackList> set = new HashMap<>(items.size());
                for (BlackList item : items) {
                    set.put(item.getHost(),item);
                }
                for (String s : detack) {
                    BlackList item = set.get(s);
                    if(item == null){
                        item = new BlackList();
                    }

                    Date releaseDt = TimeUtil.addMinute(now,forbiddenMinutes);


                    if(item.getReleaseDt() != null && item.getReleaseDt().getTime() < releaseDt.getTime()){
                        item.setReleaseDt(releaseDt);
                    }else{
                        item.setReleaseDt(null);
                    }
                    item.setReason("异常请求次数过多");
                    item.setStatus(1);
                    item.setHost(s);
                    item.setCreateDt(now);
                    blackService.saveBlackItem(item);
                }
            }
        }

    }
}
